package json;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.nio.charset.Charset;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2020/10/21 10:37
 */
public class JsonTest {
    public static void main(String[] args) {
        //通过城市名来获取省份名
        JsonTest jsonTest = new JsonTest();
        String cityName = "香格里拉";
        System.out.println(cityName+"所在的省份为"+jsonTest.getProvinceNameByCity(cityName));


    }

    public String getProvinceNameByCity(String cityName){
        if (cityName.length()>4||cityName.length()<2){
            return null;
        }
        String[] cityNames  = {"北京市","天津市","上海市","重庆市"};
        for (String name : cityNames) {
            if (name.contains(cityName)){
                return name;
            }
        }

        JSON json = JSONUtil.readJSON(new File("city.json"), Charset.forName("UTF-8"));
        JSONArray jsonArray = JSONUtil.parseArray(json);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String provinceName = jsonObject.getStr("name");
            JSONArray cityArray = jsonObject.getJSONArray("city");
            for (int j = 0; j < cityArray.size(); j++) {
                JSONObject jsonObject1 = cityArray.getJSONObject(j);
                if (jsonObject1.getStr("name").contains(cityName)){
                    return provinceName;
                }
            }
        }

        return null;
    }
}
